package com.hmjk.health.background.data;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.DatabaseHelper;
import com.hmjk.health.background.NetService;

public class UserDataUpdated extends DataUpdated{
	private static String TAG = UserDataUpdated.class.getSimpleName();
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public UserDataUpdated(HealthApp app, DataManager dm) {
		super(app, dm);
		UPDATE_TIME = 60 * 60 * 1000;
	}

	@Override
	public void setUserData(Object data) {
		// TODO Auto-generated method stub
		reqTime = 0;
		upTime = 0;
	}
	
	public long delay(){
		long curMs = System.currentTimeMillis();
		long del = curMs - upTime;
		logd("delay curMs="+curMs+" upTime="+upTime+" del="+del);
		if(del >= UPDATE_TIME){
			logd("delay 0");
			return 0;
		}else{
			logd("delay (UPDATE_TIME - del) = "+(UPDATE_TIME - del));
			return (UPDATE_TIME - del);
		}
	}
	
	private void doRequest(String uid){		
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.GET_USER_DATA);
		si.putExtra("uid", uid);
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_USER_DATA" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}
	
	@Override
	public boolean grabByUser(){
		String uid = mApp.getUID();
		logd("grabByUser uid="+uid);
		if(uid == null)
			return false;
		
		long curMs = System.currentTimeMillis();
		logd("grabByUser curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > MIN_QUERY_DUR * 1000){
			doRequest(uid);
			reqTime = curMs;
			logd("grabByUser req sent!");
			return true;
		}
		return false;
	}
	
	@Override
	public boolean grab() {
		String uid = mApp.getUID();
		logd("grab uid="+uid);
		if(uid == null)
			return false;
		
		long curMs = System.currentTimeMillis();
		logd("grab curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > UPDATE_TIME){
			doRequest(uid);
			reqTime = curMs;
			logd("grab req sent!");
			return true;
		}
		return false;
	}

	@Override
	public void receive(String stamp, String sjson) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return;
		
		if(stamp.startsWith("GET_USER_DATA")){
			if(sjson != null){
				boolean result = false;
				try {
					JSONObject json = new JSONObject(sjson);
					int code = json.getInt("code");
					if(code == 200){
						String state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							JSONObject sd = json.getJSONObject("senddata");
							JSONObject recdata = json.getJSONObject("recdata");
							if((recdata != null) && (sd != null)){
								ContentValues cv = new ContentValues();
								
								String uid = sd.getString("uid").trim();
								cv.put(DatabaseHelper.MINE_UID, uid);
								
								String account = recdata.getString("username").trim();
								
								cv.put(DatabaseHelper.MINE_ACCOUNT, account);
								
								String mobile = recdata.getString("mobileno").trim();
								cv.put(DatabaseHelper.MINE_MOBILE, mobile);
								
								String nick = "";
								if(recdata.has("nickname")){
									nick = recdata.getString("nickname").trim();
								}
								cv.put(DatabaseHelper.MINE_NICK, nick);
								
								String idcardno = "";
								if(recdata.has("useridcardno")){
									idcardno = recdata.getString("useridcardno").trim();
								}
								cv.put(DatabaseHelper.MINE_IDCARDNO, idcardno);
								
								String gender = "u";
								if(recdata.has("gender")){
									gender = recdata.getString("gender").trim();
									if(gender.equalsIgnoreCase("M")){
										gender = "m";
									}else if(gender.equalsIgnoreCase("F")){
										gender = "f";
									}else
										gender = "u";
								}
								cv.put(DatabaseHelper.MINE_GENDER, gender);
								
								String address = "";
								if(recdata.has("residentialaddress")){
									address = recdata.getString("residentialaddress").trim();
								}
								cv.put(DatabaseHelper.MINE_ADDRESS, address);
								
								String edu = "";
								if(recdata.has("educationid")){
									edu = recdata.getString("educationid");
									if(edu.length() != 1){
										edu = "";
									}
								}
								cv.put(DatabaseHelper.MINE_EDU, edu);
								
								String city = "";
								if(recdata.has("cityid")){
									city = recdata.getString("cityid").trim();
								}
								cv.put(DatabaseHelper.MINE_CITY, city);
								
								upTime = System.currentTimeMillis();
								cv.put(DatabaseHelper.MINE_TIME, upTime);
								dh.setMineTableData(uid,cv);
								dh.closeDB();
								result = true;
							}	
							
						}else{
							Log.e(TAG, "receive error state:"+state+" from network");
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
				i.putExtra("type",DataManager.F_USERDATA);
				i.putExtra("state", result);
				mApp.sendBroadcast(i);
			}
		}else if(stamp.startsWith("COMMIT_USER_DATA")){
			if(sjson != null){
				String state = "af";
				int code = 400;
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							JSONObject sd = json.getJSONObject("senddata");
							if(sd != null){
								ContentValues cv = new ContentValues();
								
								String uid = sd.getString("uid").trim();
								cv.put(DatabaseHelper.MINE_UID, uid);
								
								String account = sd.getString("username");
								cv.put(DatabaseHelper.MINE_ACCOUNT, account);
								
								String mobile = sd.getString("mobileno");
								cv.put(DatabaseHelper.MINE_MOBILE, mobile);
								
								String nick = sd.getString("nickname").trim();
								cv.put(DatabaseHelper.MINE_NICK, nick);
								
								String idcardno = sd.getString("useridcardno").trim();
								cv.put(DatabaseHelper.MINE_IDCARDNO, idcardno);
								
								String gender = sd.getString("gender").trim();
								cv.put(DatabaseHelper.MINE_GENDER, gender);
								
								String address = sd.getString("residentialaddress").trim();
								cv.put(DatabaseHelper.MINE_ADDRESS, address);
								
								String edu = sd.getString("educationid");
								cv.put(DatabaseHelper.MINE_EDU, edu);
								
								String city = sd.getString("cityid").trim();
								cv.put(DatabaseHelper.MINE_CITY, city);
								
								upTime = System.currentTimeMillis();
								cv.put(DatabaseHelper.MINE_TIME, upTime);
								
								dh.setMineTableData(uid,cv);
								dh.closeDB();
							}	
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_USERDATA);
				i.putExtra("state", state);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
					
		}
	}

	@Override
	public JSONObject check(String[] arg) {
		JSONObject ret = null;
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return null;
		
		Cursor c = dh.queryMineTableData();
		if(c.getCount() > 0){
			c.moveToFirst();
			
			String ac = c.getString(c.getColumnIndex(DatabaseHelper.MINE_ACCOUNT));
			String mobile = c.getString(c.getColumnIndex(DatabaseHelper.MINE_MOBILE));
			String nick = c.getString(c.getColumnIndex(DatabaseHelper.MINE_NICK));
			String idcard = c.getString(c.getColumnIndex(DatabaseHelper.MINE_IDCARDNO));
			String gender = c.getString(c.getColumnIndex(DatabaseHelper.MINE_GENDER));
			String addr = c.getString(c.getColumnIndex(DatabaseHelper.MINE_ADDRESS));
			String edu = c.getString(c.getColumnIndex(DatabaseHelper.MINE_EDU));
			String city = c.getString(c.getColumnIndex(DatabaseHelper.MINE_CITY));
			upTime = c.getLong(c.getColumnIndex(DatabaseHelper.MINE_TIME));
			
			try {
				ret = new JSONObject();
				ret.put("ac", ac);
				ret.put("mobile", mobile);
				ret.put("nick", nick);
				ret.put("idcard", idcard);
				ret.put("gender", gender);
				ret.put("addr", addr);
				ret.put("edu", edu);
				ret.put("city", city);
				ret.put("uptime", upTime);
			
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				ret = null;
			}
		}
		c.close();
		dh.closeDB();
		return ret;
	}
	
	@Override
	public boolean commit(Object data) {
		String uid = mApp.getUID();
		
		if((uid == null) || uid.isEmpty())
			return false;
			
		JSONObject json = (JSONObject)data;
		if(json == null)
			return false;
		
		try {
			Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
			si.putExtra("sub_act", NetService.COMMIT_USER_DATA);
			si.putExtra("uid", uid);
			String ac = json.getString("ac");
			si.putExtra("username", ac);
			String mobile = json.getString("mobile");
			si.putExtra("mobileno",mobile);
			String nick = json.getString("nick");
			si.putExtra("nickname", nick);
			String idcard = json.getString("idcard");
			si.putExtra("useridcardno", idcard);
			String gender = json.getString("gender").toLowerCase();
			si.putExtra("gender", gender);
			String addr = json.getString("addr");
			si.putExtra("residentialaddress", addr);
			String edu = json.getString("edu");
			si.putExtra("educationid", edu);
			String city = json.getString("city");
			si.putExtra("cityid", city);
			si.putExtra("occupationid", "");
			si.putExtra("positionid", "");
			
			Time t = new Time();
			t.setToNow();
			String stamp = "COMMIT_USER_DATA" + t.toString(); 
			si.putExtra("stamp",stamp);
			mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
			mApp.startService(si);
			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}

}
